package 排序算法;

import java.util.Arrays;

//用荷兰国旗问题，加利用随机性，来改进快速排序

//时间复杂度O(N*logN)， 额外空间复杂度O(logN)
public class 改进的快速排序 {
	public static void quickSort(int[] arr) {
		if (arr==null || arr.length<2) {
			return;
		}
		quickSort(arr,0,arr.length-1);
	}

	private static void quickSort(int[] arr, int l, int r) {
		if (l<r) {
//			为了将快排受数据状态的影响变成一个概率性的，随机的
			swap(arr, l + (int) (Math.random() * (r - l + 1)), r); //把原序列随机交换，就变成了随机快排
			int[] p=partition(arr,l,r);
			quickSort(arr, l, p[0]-1);
			quickSort(arr, p[1]+1, r);
		}
		
	}

	private static int[] partition(int[] arr, int l, int r) {
		int less=l-1;
		int more=r;
		//以arr[r]为基准值
		// [ <=x | >x| x ]
		while (l<more) { //more不参与循环
			if (arr[l]<arr[r]) {
				swap(arr,++less,l++);
			}else if (arr[l]>arr[r]) {
				swap(arr, l, --more);
			}else {
				l++;
			}
		}
		// [ <=x | >x | x ] 转换为  [ <=x | x | >x ]
		swap(arr, more, r);
		return new int[] {less+1,more};

	}
	
	private static void swap(int[] arr, int i, int j) {
		int temp=arr[i];
		arr[i]=arr[j];
		arr[j]=temp;
	}
	
	// for test
		public static void comparator(int[] arr) {
			Arrays.sort(arr);
		}

		// for test
		public static int[] generateRandomArray(int maxSize, int maxValue) {
			int[] arr = new int[(int) ((maxSize + 1) * Math.random())];
			for (int i = 0; i < arr.length; i++) {
				arr[i] = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
			}
			return arr;
		}

		// for test
		public static int[] copyArray(int[] arr) {
			if (arr == null) {
				return null;
			}
			int[] res = new int[arr.length];
			for (int i = 0; i < arr.length; i++) {
				res[i] = arr[i];
			}
			return res;
		}

		// for test
		public static boolean isEqual(int[] arr1, int[] arr2) {
			if ((arr1 == null && arr2 != null) || (arr1 != null && arr2 == null)) {
				return false;
			}
			if (arr1 == null && arr2 == null) {
				return true;
			}
			if (arr1.length != arr2.length) {
				return false;
			}
			for (int i = 0; i < arr1.length; i++) {
				if (arr1[i] != arr2[i]) {
					return false;
				}
			}
			return true;
		}

		// for test
		public static void printArray(int[] arr) {
			if (arr == null) {
				return;
			}
			for (int i = 0; i < arr.length; i++) {
				System.out.print(arr[i] + " ");
			}
			System.out.println();
		}

		// for test
		public static void main(String[] args) {
			int testTime = 500000;
			int maxSize = 100;
			int maxValue = 100;
			boolean succeed = true;
			for (int i = 0; i < testTime; i++) {
				int[] arr1 = generateRandomArray(maxSize, maxValue);
				int[] arr2 = copyArray(arr1);
				quickSort(arr1);
				comparator(arr2);
				if (!isEqual(arr1, arr2)) {
					succeed = false;
					printArray(arr1);
					printArray(arr2);
					break;
				}
			}
			System.out.println(succeed ? "True" : "False!");

			int[] arr = generateRandomArray(maxSize, maxValue);
			printArray(arr);
			quickSort(arr);
			printArray(arr);

		}


}
